import React, { useEffect, useRef, useState } from 'react';
import styles from './index.module.scss';
import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import { useDispatch } from 'react-redux';
import {
  clearArticleAction,
  clearCommentsAction,
  getCommentsByIdAction,
  getDetailByIdAction,
} from '@/store/action/detail';
import { useParams } from 'react-router-dom';
import { useAppSelector } from '@/store';
import DOMPurify from 'dompurify';
import dayjs from 'dayjs';
import Skeleton from '@/components/Skeleton';
import hljs from 'highlight.js';
import 'highlight.js/styles/vs2015.css';
import classnames from 'classnames';
import NoComment from './components/NoComment';
import CommentItem from './components/CommentItem';
import MyLoading from '@/components/Loading';
import CommentFooter from './components/CommentFooter';
import { Popup } from 'antd-mobile';
import CommentReply from './components/CommentReply';
import Share from './components/Share';

/*
  学习目标：实现分享弹出层的显示与隐藏

*/

export default function Article() {
  const dispatch = useDispatch();
  const { id } = useParams<{ id: string }>();
  useEffect(() => {
    dispatch(getDetailByIdAction(id));
  }, [dispatch, id]);

  const { detail } = useAppSelector((state) => state.article);
  const { isLoading, commentList, originComment } = useAppSelector((state) => state.comment);

  const [navAuthorShow, setNavAuthorShow] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);
  const authorRef = useRef<HTMLDivElement>(null);

  const scrollFn = () => {
    const top = authorRef.current?.getBoundingClientRect().top as number;
    if (top > 10) {
      setNavAuthorShow(false);
    } else {
      setNavAuthorShow(true);
    }
  };

  useEffect(() => {
    if (!detail.art_id) return;
    wrapRef.current?.addEventListener('scroll', scrollFn);

    const warpDom = wrapRef.current;
    return () => {
      warpDom!.removeEventListener('scroll', scrollFn);
    };
  }, [detail.art_id]);

  const commentRef = useRef<HTMLDivElement>(null);

  const handleScrollTop = () => {
    if (!wrapRef.current) return;
    wrapRef.current.scrollTop = commentRef.current!.offsetTop - 50;
  };

  useEffect(() => {
    if (!detail.art_id) return;
    hljs.configure({
      ignoreUnescapedHTML: true,
    });

    const codes = document.querySelectorAll('.dg-html pre code');
    if (codes.length) {
      return codes.forEach((el) => {
        hljs.highlightElement(el as any);
      });
    }

    const pres = document.querySelectorAll('.dg-html pre');
    if (pres.length) {
      return pres.forEach((el) => {
        hljs.highlightElement(el as any);
      });
    }
  }, [detail.art_id, dispatch]);

  useEffect(() => {
    if (!detail.art_id) return;
    dispatch(getCommentsByIdAction({ type: 'a', source: detail.art_id }));
  }, [dispatch, detail.art_id]);

  useEffect(() => {
    return () => {
      dispatch(clearArticleAction());
      dispatch(clearCommentsAction());
    };
  }, [dispatch]);

  const [shareVisible, setShareVisible] = useState(false);
  const handleShowShare = () => setShareVisible(true);
  const handleCloseShare = () => setShareVisible(false);
  return (
    <div className={styles.root} id="box">
      <div className="root-wrapper">
        <NavBar right={<Icon type="icongengduo" />}>
          {navAuthorShow && (
            <div className="nav-author">
              <img src={detail.aut_photo} alt="" />
              <span className="name">{detail.aut_name}</span>
              <span className={classnames('follow', detail.is_followed ? 'followed' : '')}>
                {detail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>

        {!!detail.art_id ? (
          <div className="wrapper" ref={wrapRef}>
            <div className="article-wrapper">
              <div className="header">
                <h1 className="title">{detail.title}</h1>

                <div className="info">
                  <span>{dayjs(detail.pubdate).format('YYYY-MM-DD')}</span>
                  <span>{detail.read_count} 阅读</span>
                  <span>{detail.comm_count} 评论</span>
                </div>

                <div className="author" ref={authorRef}>
                  <img src={detail.aut_photo} alt="" />
                  <span className="name">{detail.aut_name}</span>
                  <span className="follow">关注</span>
                </div>
              </div>

              <div className="content">
                <div
                  className="content-html dg-html"
                  dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(detail.content) }}
                ></div>
                <div className="date">发布文章时间：{dayjs().from(detail.pubdate)}</div>
                <div className="divider"></div>
                <div className="comment" ref={commentRef}>
                  <div className="comment-header">
                    <span>全部评论（{detail.comm_count}）</span>
                    <span>{detail.like_count} 点赞</span>
                  </div>
                  {isLoading && <MyLoading />}
                  {detail.comm_count === 0 ? (
                    <NoComment />
                  ) : (
                    <div className="comment-list">
                      {commentList.map((item) => (
                        <CommentItem comment={item} key={item.com_id} />
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        ) : (
          <Skeleton></Skeleton>
        )}
      </div>
      <CommentFooter onShare={handleShowShare} onClick={handleScrollTop} articleData={detail} />
      <Popup destroyOnClose visible={!!originComment.com_id} position="right">
        <CommentReply></CommentReply>
      </Popup>

      <Popup visible={shareVisible}>
        <Share onClose={handleCloseShare}></Share>
      </Popup>
    </div>
  );
}
